package org.jflame.web.servlet;

import java.io.IOException;

import org.apache.commons.lang3.ArrayUtils;
import org.jflame.commons.file.FileHelper;
import org.jflame.commons.file.MimeTypes;
import org.jflame.commons.util.IOHelper;
import org.jflame.commons.util.StringHelper;
import org.jflame.context.filemanager.FileManagerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 读取本地图片输出servlet.
 * 
 * @deprecated 废除,请使用FileServlet替换
 */
@SuppressWarnings("serial")
@Deprecated
public class LoadImageServlet extends HttpServlet {

    private final Logger log = LoggerFactory.getLogger(LoadImageServlet.class);
    // private String savePath;

    @Override
    public void init(ServletConfig config) throws ServletException {
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 从URL读取文件路径,拼接本地路径,读取文件流输出到客户端
        String imgRelativePath = request.getPathInfo();
        boolean isNotFound = true;
        if (StringHelper.isNotEmpty(imgRelativePath)) {
            String ext = FileHelper.getExtension(imgRelativePath, false);
            if (!ArrayUtils.contains(MimeTypes.WEB_IMAGE_EXTENSIONS, ext)) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, "不支持的图片格式");
                return;
            }

            response.setContentType(MimeTypes.getInstance()
                    .getMimetype(imgRelativePath));
            byte[] fileBytes = FileManagerFactory.getCurrentManager()
                    .readBytes(imgRelativePath);
            if (fileBytes != null) {
                try (ServletOutputStream servletOutStream = response.getOutputStream();) {
                    IOHelper.write(fileBytes, servletOutStream);
                    servletOutStream.flush();
                    isNotFound = false;
                } catch (IOException e) {
                    log.error("输出图片失败:" + imgRelativePath, e);
                    isNotFound = true;
                }
            }

        }
        if (isNotFound) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "图片不存在");
            if (log.isDebugEnabled()) {
                log.debug("图片不存在:{}", imgRelativePath);
            }
        }
    }

    public void destroy() {
        super.destroy();
    }
}
